package com.sanq.product.mcgs.filter;

import com.google.common.base.Preconditions;
import com.sanq.product.config.utils.string.MatcherUtil;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.config.utils.web.LogUtil;
import com.sanq.product.mcgs.common.Redis;
import com.sanq.product.mcgs.entity.vo.MemberVo;
import com.sanq.product.mcgs.util.RequestUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.security.enums.TokenTime;
import com.sanq.product.security.interceptors.CheckHasPermissionInterceptor;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class SecurityFilter extends CheckHasPermissionInterceptor {

    @Resource
    private JedisPoolService jedisPoolService;

    private static final int MAX = 60;  //最大限制  1分钟访问60次

    //判断token是否存在
    @Override
    public boolean checkToken(HttpServletRequest request, String token) {
        String tokenKey = Redis.ReplaceKey.getMemberTokenKey(token);
        boolean exists = jedisPoolService.exists(tokenKey);

        if (exists) {
            jedisPoolService.expire(tokenKey, TokenTime.TOKEN_TIME.getTime());
            RequestUtil.add(JsonUtil.json2Obj(jedisPoolService.get(tokenKey), MemberVo.class));
            jedisPoolService.expire(Redis.ReplaceKey.getButtonPermissionKey(RequestUtil.get().getId()), TokenTime.TOKEN_TIME.getTime());
            jedisPoolService.expire(Redis.ReplaceKey.getTreePermissionKey(RequestUtil.get().getId()), TokenTime.TOKEN_TIME.getTime());
        }

        return exists;
    }

    //判断是否恶意刷新
    @Override
    public boolean checkIp(HttpServletRequest request, String ip) {

        String ipKey = Redis.ReplaceKey.getCheckIpKey(ip, request.getRequestURI());

        if (jedisPoolService.zrank(Redis.RedisKey.BLOCK_IP_SET, ip)) {
            return true;
        }

        String ipCountTmp = jedisPoolService.get(ipKey);
        int ipCount = StringUtil.toInteger(ipCountTmp != null ? ipCountTmp : 0);

        if (ipCount > MAX) {
            jedisPoolService.putSet(Redis.RedisKey.BLOCK_IP_SET, 1, ip);
            jedisPoolService.delete(ipKey);
            return true;
        }

        jedisPoolService.incrAtTime(ipKey, MAX);

        return false;
    }

    //判断是否有当前权限
    @Override
    protected boolean checkHasThisUrl(HttpServletRequest httpServletRequest, String uri, String token) {

        //忽略当前链接
        if (uri.contains("/api/member/getInfoByToken") ||
                uri.contains("/api/member/updatePwd") ||
                uri.contains("/api/permission/findPermissionByMemberId")) {
            return true;
        }

        //如果是update， 需要替换掉id值
        String group = MatcherUtil.group("-?[1-9]\\d*$", uri, 0);
        if (!StringUtil.isEmpty(group))
            uri = uri.replace(group, "*");

//        LogUtil.getInstance(getClass()).i(uri);

        List<String> permissionUrlList = JsonUtil.json2ObjList(jedisPoolService.get(Redis.ReplaceKey.getButtonPermissionKey(RequestUtil.get().getId())), String.class);

        Preconditions.checkNotNull(permissionUrlList);

        return permissionUrlList.contains(uri);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
        RequestUtil.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        RequestUtil.remove();
    }
}
